package logic

import (
	"context"
	"errors"
	"hemabox/models/mysql"

	"hemabox/hemarpc/hemarpc"
	"hemabox/hemarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HemaAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHemaAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HemaAddLogic {
	return &HemaAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建
func (l *HemaAddLogic) HemaAdd(in *hemarpc.HemaAddRequest) (*hemarpc.HemaAddResponse, error) {
	// todo: add your logic here and delete this line

	var findHema mysql.Hema
	Begin := mysql.DB.Begin()

	err := findHema.FindHemaByHemaName(mysql.DB, in.HemaName)
	if err == nil {
		Begin.Rollback()
		return nil, errors.New("已存在该商品,禁止重复性录入")
	}
	var class mysql.Class
	if err = class.FindClassByClassName(mysql.DB, in.ClassName); err != nil {
		class = mysql.Class{
			ClassName: in.ClassName,
		}
		if err = class.ClassAdd(mysql.DB); err != nil {
			Begin.Rollback()
			return nil, errors.New("分类添加失败")
		}
	}

	hema := mysql.Hema{
		HemaName:    in.HemaName,
		HemaContent: in.HemaContent,
		HemaPrice:   float64(in.HemaPrice),
		HemaClassId: int(class.ID),
	}
	if err = hema.HemaAdd(mysql.DB); err != nil {
		Begin.Rollback()
		return nil, errors.New("商品添加失败")
	}

	if err = Begin.Commit().Error; err != nil {
		Begin.Rollback()
		return nil, errors.New("提交事务失败")
	}

	return &hemarpc.HemaAddResponse{
		HemaId: int64(hema.ID),
	}, nil
}
